package com.jzg.jcptadmin.presenter;

import com.jzg.jcptadmin.Utils.ChineseUtil;
import com.jzg.jcptadmin.Utils.SubmitValueVerification;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BasePresenter;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.Make;
import com.jzg.jcptadmin.data.vo.MakeList;
import com.jzg.jcptadmin.data.vo.Model;
import com.jzg.jcptadmin.data.vo.ModelCategory;
import com.jzg.jcptadmin.data.vo.ModelList;
import com.jzg.jcptadmin.viewinterface.BrandInterface;
import com.orhanobut.logger.Logger;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by wangyd on 15/12/23.
 * 品牌列表逻辑
 */
public class BrandPresenter extends BasePresenter<BrandInterface> {
    private final DataManager mDataManager;
    private Subscription mSubscription;
    private BrandInterface mView;

    public BrandPresenter(DataManager instance) {
        super();
        mDataManager = instance;
    }

    @Override
    public void attachView(BrandInterface mvpView) {
        super.attachView(mvpView);
        this.mView = mvpView;
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mSubscription != null) mSubscription.unsubscribe();
    }

    /**
     * 加载品牌数据
     */
    public void loadBrand() {
        checkViewAttached();
        Map<String, String> params = mView.getBrandParams();
        if (SubmitValueVerification.isEmpty(params)) return;
        if (!AppContext.isNetWork) {
            mView.showError(Constant.errr_net);
            return;
        }
        mSubscription = mDataManager.loadBrand(params).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<MakeList>() {
                               @Override
                               public void onCompleted() {
//                                   Logger.i("oncomplete");
                               }

                               @Override
                               public void onError(Throwable e) {
                                   if(e!=null&&mView!=null){
                                       mView.showError(e.toString());
                                   }

                               }

                               @Override
                               public void onNext(MakeList makeList) {
//                                   Logger.i(makeList.toString());
                                   if (makeList.getStatus() == Constant.SUCCESS) {

                                       ArrayList<Make> makes = makeList.getMakeList();
                                       if (makes != null) {
                                           //设置品牌列表数据用于ItemClick
                                           if (!mView.readFromCache(makeList)) {  //如果缓存与网络不一致，更新列表
                                               showMake(makes);
                                           }

                                       }
                                   } else {
                                       mView.showError(makeList.getMsg());
                                   }
                               }


                           }

                );
    }

    public void showMake(ArrayList<Make> makes) {
        mView.setBrands(makes);
        ArrayList<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
        Map<String, Integer> indexData = new HashMap<String, Integer>();
        //显示分组数据用于分组adapter
        getItems(makes, items);
        mView.showBrand(items);

        //设置index索引数据用于index索引监听
        getIndexData(items, indexData);
        mView.setIndexData(indexData);
    }

    private void getIndexData(ArrayList<Map<String, Object>> items, Map<String, Integer> indexData) {
        for (int i = 0; i < items.size(); i++) {
            // 当前汉语拼音首字母
            String currentStr = items.get(i).get("Sort").toString();
            // 上一个汉语拼音首字母，如果不存在为“ ”
            String previewStr = (i - 1) >= 0 ? items.get(i - 1).get("Sort")
                    .toString() : " ";
            if (!previewStr.equals(currentStr)) {
                String name = items.get(i).get("Sort").toString();
                indexData.put(name, i);
            }
        }
    }

    private void getItems(ArrayList<Make> makes, ArrayList<Map<String, Object>> items) {
        Map<String, Object> map = null;
        for (int i = 0; i < makes.size(); i++) {
            map = new HashMap<String, Object>();
            map.put("name", makes.get(i).getMakeName());
            map.put("fontColor", mView.getDefaultFontColor());
            map.put("logo", makes.get(i).getMakeLogo());
//            String contactSort = ChineseUtil
//                    .getFullSpell(map.get("name").toString())
//                    .toUpperCase().substring(0, 1);

            String contactSort =  makes.get(i).getGroupName();  //字母以后台返回的为准，本地不处理汉字转拼音

            map.put("Sort", contactSort);
            items.add(map);
        }
//        Comparator comp = new Mycomparator();   //品牌顺序一后台返回为准，本地不在排序
//        Collections.sort(items, comp);
    }

    /**
     * 加载车系数据
     */
    public void loadModel() {
        checkViewAttached();
        Map<String, String> params = mView.getModelParams();
        if (SubmitValueVerification.isEmpty(params)) return;
        if (!AppContext.isNetWork) {
            mView.showError(Constant.errr_net);
            return;
        }
        mSubscription = mDataManager.loadModel(params)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe(new Observer<ModelList>() {
                    @Override
                    public void onCompleted() {
                        Logger.i("loadModel onCompleted.");
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e.toString());
                    }

                    @Override
                    public void onNext(ModelList modelList) {
                        if (modelList.getStatus() == Constant.SUCCESS) {
                            ArrayList<ModelCategory> modelCategorys = modelList.getManufacturerList();
                            ArrayList<Model> mModels = new ArrayList<Model>();
                            ArrayList<String> mModelsGroupNames = new ArrayList<String>();
                            for (ModelCategory category : modelCategorys) {
                                Model group = new Model();
                                String groupName = category.getManufacturerName();
                                mModelsGroupNames.add(groupName);
                                group.setName(groupName);
                                group.setManufacturerName(Constant.IS_TITLE);
                                group.setFontColor(mView.getDefaultFontColor());
                                //增加厂商
                                mModels.add(group);
                                //增加厂商下关联的车系
                                for (Model item : category.getModelList()) {
                                    item.setFontColor(mView.getDefaultFontColor());
                                    mModels.add(item);
                                }
                            }

                            mView.setModels(mModels);
                            mView.setModelsGroupNames(mModelsGroupNames);
                            mView.showModel();
                        } else {
                            mView.showError(modelList.getMsg());
                        }
                    }
                });
    }

    // 按中文拼音排序
    public class Mycomparator implements Comparator {
        @Override
        public int compare(Object o1, Object o2) {
            Map<String, Object> c1 = (Map<String, Object>) o1;
            Map<String, Object> c2 = (Map<String, Object>) o2;
            Comparator cmp = Collator.getInstance(java.util.Locale.ENGLISH);
            return cmp.compare(c1.get("Sort"), c2.get("Sort"));
        }
    }
}

